package com.fansea.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.awt.*;
import java.io.*;
public class WeatherUtil {
    public static String getWeather(String area){
        try {
            String encode = "";
            String keyencode = "";
            try {
                 encode = URLEncoder.encode(area, "UTF-8");
                keyencode = URLEncoder.encode("20da1faad4292c14bdb0665b790ceec6", "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            //请求头
            Map<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type","application/json");

            JSONObject myJsonObject = new JSONObject();
            HttpResponse httpResponse = AliHttpUtils.doGet("https://restapi.amap.com/", "/v3/weather/weatherInfo?key=20da1faad4292c14bdb0665b790ceec6&city=武汉", "GET", headers, new HashMap<>());
//        String weather = HttpRequestUtil.doGet("https://restapi.amap.com/v3/weather/weatherInfo?key="+keyencode+"&city="+encode);
            //获取气温，天气状况
            String weather = EntityUtils.toString(httpResponse.getEntity());
            JSONObject jsonObject = JSON.parseObject(weather);
            String lives = jsonObject.getString("lives");
            JSONArray jsonArray = JSON.parseObject(lives, JSONArray.class);
            String o = String.valueOf(jsonArray.get(0));

            jsonObject = JSON.parseObject(o);

            String type = jsonObject.getString( "weather");
            String low = jsonObject.getString( "temperature");
            String wind = jsonObject.getString( "winddirection");
            String windlevl = jsonObject.getString( "windpower");
            String time = jsonObject.getString( "reporttime");

            return                  "天气："+type+"\n气温："+low+"\n风向："+wind+"\n风级："+windlevl+"\n播报时间："+time;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "获取天气失败";
    }




}
